import os
from django.conf import settings
from django.http import Http404
from django.shortcuts import render
from django.template import Template
from django.utils._os import safe_join
import re
import random

regular_search_mobile_device = 'Android|iPhone'
reqularSearchMobileDevicePattern = re.compile(regular_search_mobile_device, re.MULTILINE)
def get_page_or_404(name):
	"""Return page content as a Django template or raise 404 error."""
	try:
		file_path = safe_join(settings.SITE_PAGES_DIRECTORY, name)
		print (file_path)
	except ValueError:
		raise Http404('Page Not Found')
	else:
		if not os.path.exists(file_path):
			raise Http404('Page Not Found')
	with open(file_path, 'r') as f:
		page = Template(f.read())
	return page

def page(request, slug='index'):
	print('Call page funtion')
	"""Render the requested page if found."""
	file_name = '{}.html'.format(slug)
	page = get_page_or_404(file_name)
	context = {
		'slug': slug,
		'page': page,
		}
	print (context)
	return render(request, 'page.html', context)

def generator(request, slug='index'):
	"""Render the requested page if found."""
	file_name = '{}.html'.format(slug)
	page = get_page_or_404(file_name)
	imgDirPath = safe_join(settings.SITE_PAGES_DIRECTORY, 'Logo')
	logoList = os.listdir(imgDirPath)
	randomIndexA = random.randint(0, len(logoList) - 1)
	randomIndexB = random.randint(0, len(logoList) - 1)
	fullTeamA = logoList[randomIndexA]
	fullTeamB = logoList[randomIndexB]
	(teamA, extentionA) = os.path.splitext(fullTeamA)
	(teamB, extentionB) = os.path.splitext(fullTeamB)
	imgA = '/static/Logo/' + logoList[randomIndexA]
	imgB = '/static/Logo/' + logoList[randomIndexB]
	mobileDevice = False
	agent = request.META.get('HTTP_USER_AGENT', None)
	searchMobileDeviceResult = reqularSearchMobileDevicePattern.search(agent)
	print (agent)
	print (searchMobileDeviceResult)
	if (searchMobileDeviceResult is None):
		mobileDevice = False
	else:
		mobileDevice = True
	context = {
		'slug': slug,
		'page': page,
		'imgA': imgA,
		'imgB': imgB,
		'teamA': teamA,
		'teamB': teamB,
		'mobileDevice':mobileDevice,
		}
	print (context)
	return render(request, 'page.html', context)